﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace Utilites
{
    public class MD5String
    {
        private string _original_string;
        private string _md5_string;

        public string Original
        {
            get
            {
                return _original_string;
            }
            set
            {
                if (_original_string == null)
                {
                    throw new ArgumentNullException("MD5 String cannot be null");
                }
                _original_string = value;
                _md5_string = GetHash(_original_string);
            }
        }

        public string MD5Hash
        {
            get
            {
                return _md5_string;
            }
        }

        public MD5String(string original)
        {
            this.Original = original;
        }

        public static implicit operator string(MD5String src)
        {
            return src.MD5Hash;
        }

        public static implicit operator MD5String(string src)
        {
            return new MD5String(src);
        }

        #region Stolen
        private static string GetHash(string s)
        {
            MD5 sec = new MD5CryptoServiceProvider();
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] bt = enc.GetBytes(s);
            return GetHexString(sec.ComputeHash(bt));
        }

        private static string GetHexString(byte[] bt)
        {
            StringBuilder s = new StringBuilder();
            for (int i = 0; i < bt.Length; i++)
            {
                byte b = bt[i];
                int n, n1, n2;
                n = (int)b;
                n1 = n & 15;
                n2 = (n >> 4) & 15;
                if (n2 > 9)
                    s.Append(((char)(n2 - 10 + (int)'A')));
                else
                    s.Append(n2);
                if (n1 > 9)
                    s.Append(((char)(n1 - 10 + (int)'A')));
                else
                    s.Append(n1);
            }
            return s.ToString();
        }
        #endregion
    }
}
